package com.itheima.bos.web.action;

import com.itheima.bos.domain.User;
import com.itheima.bos.service.IUserService;
import com.itheima.bos.service.impl.UserServiceImpl;
import com.itheima.bos.utils.BOSContext;
import com.itheima.bos.utils.MD5Utils;
import com.itheima.bos.web.action.base.BaseAction;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by Mr.King on 2017/3/7.
 */
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {
    
    @Autowired
    private IUserService service;

    /**
     * 验证码
     */
    private String checkcode;
    public void setCheckcode(String checkcode) {
        this.checkcode = checkcode;
    }

    /**
     * 接收角色
     */
    private String[] roleIds;
    public void setRoleIds(String[] roleIds) {
        this.roleIds = roleIds;
    }

    /**
     * 登录
     * @return
     */
    public String login(){
        String key = (String) ServletActionContext.getRequest().getSession().getAttribute("key");
        if (StringUtils.isBlank(checkcode) || !checkcode.equals(key)){
            this.addActionError(this.getText("checkCodeError"));
            return "login";
        }else {
            /*User user = service.login(model);
            if (user != null){
                ServletActionContext.getRequest().getSession().setAttribute("user",user);
                return "index";
            }else {
                this.addActionError(this.getText("loginError"));
                return "login";
            }*/
            //使用shiro提供的方式进行权限认证
            //获得当前用户对象，现在状态为“未认证”
            Subject subject = SecurityUtils.getSubject();
            String username = model.getUsername();
            String password = model.getPassword();
            password = MD5Utils.md5(password);
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);//调用安全管理器，安全管理器调用Realm
                User user = (User) subject.getPrincipal();
                //登录成功，存session，跳首页
                ServletActionContext.getRequest().getSession().setAttribute("user",user);
                return "index";
            }catch (UnknownAccountException e) {
                e.printStackTrace();
                //用户名不存在，跳转到登录页面
                this.addActionError(this.getText("notExitUser"));
                return "login";
            }catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                // 密码错误，跳转到登录页面
                this.addActionError(this.getText("passwordErr"));
                return "login";
            }
        }
    }

    /**
     * 退出登录
     * @return
     */
    public String logOut(){
        ServletActionContext.getRequest().getSession().removeAttribute("user");
        return "login";
    }

    /**
     * 修改密码
     * @return
     */
    public String editPassword(){
        //保存密码修改
        String password = model.getPassword();
        User user = BOSContext.getLoginUser();
        String id = user.getId();
        String flag = "0";
        try {
            service.editPassword(password,id);
            //密码修改后需要重新登录
            ServletActionContext.getRequest().getSession().invalidate();
        }catch (Exception e){
            flag = "1";
            e.printStackTrace();
        }
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().print(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return NONE;
    }

    /**
     * 保存用户
     */
    public String save(){
        service.save(model,roleIds);
        return "list";
    }

    /**
     * 展示用户
     */
    public String list() throws IOException {
        List<User> list = service.findAll();

        String[] arr = new String[]{"password","remark","birthday","noticebills","roles"};
        toJSON(list,arr);
        return NONE;
    }
}
